package com.smfx.yxt.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.smfx.yxt.common.Const;
import com.smfx.yxt.common.enums.GuideStatus;
import com.smfx.yxt.common.enums.NoticeType;
import com.smfx.yxt.common.enums.RelationType;
import com.smfx.yxt.common.enums.SendeeType;
import com.smfx.yxt.daoSqlserver.AttachmentListMapper;
import com.smfx.yxt.daoSqlserver.NoticeRecordMapper;
import com.smfx.yxt.daoSqlserver.NoticeSendeeRecordMapper;
import com.smfx.yxt.model.AttachmentList;
import com.smfx.yxt.model.NoticeRecord;
import com.smfx.yxt.model.NoticeSendeeRecord;
import com.smfx.yxt.model.StudentInfo;
import com.smfx.yxt.page.Page;
import com.smfx.yxt.reqVo.NoticeQueryVO;
import com.smfx.yxt.reqVo.NoticeReqVO;
import com.smfx.yxt.reqVo.NoticeSendeeReqVO;
import com.smfx.yxt.service.INoticeService;
import com.smfx.yxt.view.NoticeRecordView;
import com.smfx.yxt.wechat.utils.TemplateUtil;

@Service("noticeService")
public class NoticeServiceImpl implements INoticeService {
	
	@Autowired
	private NoticeRecordMapper noticeRecordMapper;
	@Autowired
	private AttachmentListMapper attachmentListMapper;
	@Autowired
	private NoticeSendeeRecordMapper noticeSendeeRecordMapper;

	@Override
	public int insertSelective(NoticeRecord record) {
		return noticeRecordMapper.insertSelective(record);
	}

	@Override
	public NoticeRecord selectByPrimaryKey(Integer id) {
		return noticeRecordMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(NoticeRecord record) {
		return noticeRecordMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public int createNotice(NoticeReqVO reqVO, NoticeRecord record) {
		noticeRecordMapper.insertSelective(record);
		AttachmentList attachment = new AttachmentList();
		attachment.setTeacherId(record.getSenderId());
		attachment.setRelationType(RelationType.NOTICE.getCode());
		attachment.setRelationId(Long.valueOf(record.getId()));
		attachmentListMapper.updateRelationId(attachment);
		new Thread(new TeacherNoticeExecutor(reqVO, record)).start();
		return 1;
	}
	
	@Override
	public int updatePrincipalSend(NoticeReqVO reqVO, NoticeRecord record) {
		noticeRecordMapper.updateByPrimaryKeySelective(record);
		new Thread(new TeacherNoticeExecutor(reqVO, record)).start();
		return 1;
	}
	
	@Override
	public int repeatNotice(NoticeReqVO reqVO, NoticeRecord record) {
		new Thread(new TeacherNoticeExecutor(reqVO, record)).start();
		return 1;
	}
	
	class TeacherNoticeExecutor implements Runnable {
		
		private NoticeReqVO reqVO;
		
		private NoticeRecord record;
		
		public TeacherNoticeExecutor(NoticeReqVO reqVO, NoticeRecord record) {
			this.reqVO = reqVO;
			this.record = record;
		}

		@Override
		public void run() {
			try { 
				List<NoticeSendeeRecord> list = null;
				if(record.getGuideStatus() != null && GuideStatus.SENDED.getCode().equals(record.getGuideStatus())) {
					list = noticeSendeeRecordMapper.selectListByNoticeId(record.getId());
					for(NoticeSendeeRecord notice : list) {
						if(notice.getSendeeId().intValue() == record.getGuideId()) {
							list.remove(notice);
							break;
						}
					}
				}else if(reqVO.isRepeat()) {
					list = noticeSendeeRecordMapper.selectListForNoReadByNoticeId(record.getId());
				}else {
					NoticeSendeeReqVO sendee = new NoticeSendeeReqVO();
					sendee.setNoticeId(record.getId());
					sendee.setNoticeType(record.getNoticeType());
					sendee.setSendeeType(reqVO.getSendModel());
					sendee.setStudyType(reqVO.getStudyType());
					sendee.setIds(reqVO.getIds());
					if (record.getNoticeType() == NoticeType.NOTICE_CLASS.getCode()) {
						//班级通知可以作用到某个学生
						noticeSendeeRecordMapper.insertParentNotice(sendee);
					} else if(record.getNoticeType() == NoticeType.NOTICE_HOMEWORK.getCode()) {
						List<StudentInfo> gradeClassList = new ArrayList<>();
						for(String itm : reqVO.getIds()) {
							String[] array = itm.split("_");
							StudentInfo student = new StudentInfo();
							student.setGrade(Integer.valueOf(array[0]));
							student.setClazz(Integer.valueOf(array[1]));
							gradeClassList.add(student);
						}
						sendee.setGradeClassList(gradeClassList);
						noticeSendeeRecordMapper.insertParentNoticeForClass(sendee);
					} else if(record.getNoticeType() == NoticeType.NOTICE_EXECUTIVE.getCode()) {
						//行政通知可以发送给老师也可以发送给家长
						//发送给家长
						if(reqVO.getSendModel() == SendeeType.PARENT.getCode()) {
							List<StudentInfo> gradeClassList = new ArrayList<>();
							for(String itm : reqVO.getIds()) {
								String[] array = itm.split("_");
								StudentInfo student = new StudentInfo();
								student.setGrade(Integer.valueOf(array[0]));
								student.setClazz(Integer.valueOf(array[1]));
								gradeClassList.add(student);
							}
							sendee.setGradeClassList(gradeClassList);
							noticeSendeeRecordMapper.insertParentNoticeForClass(sendee);
						}//发送给老师
						else if(reqVO.getSendModel() == SendeeType.TEACHER.getCode()) {
							noticeSendeeRecordMapper.insertTeacherNotice(sendee);
						}
					} else {
						//其他通知只能发个老师
						noticeSendeeRecordMapper.insertTeacherNotice(sendee);
					}
					list = noticeSendeeRecordMapper.selectListByNoticeId(record.getId());
				}
				String content = record.getContent();
				if(content.length() > 50) {
					content = content.substring(0, 50) + "...";
				}
				String reqUrl = Const.BASEPATH;
				if(reqVO.getSendModel() == SendeeType.PARENT.getCode()) {
					reqUrl += Const.STUDENT_ROLE;
				}else {
					reqUrl += Const.TEACHER_ROLE;
				}
				if(record.getNoticeType() == NoticeType.NOTICE_FILEAROUND.getCode()){
					reqUrl += "/notice/fileAround/detail/" + record.getId();
				}else {
					reqUrl += "/notices/detail/" + record.getId();
				}
				for(NoticeSendeeRecord item : list) {
					String currReqUrl = reqUrl;
					if(reqVO.getSendModel() == SendeeType.PARENT.getCode()) {
						currReqUrl = currReqUrl + "?sid=" + item.getStudentId();
					}
					if(record.getNoticeType() == NoticeType.NOTICE_CLASS.getCode()) {
						TemplateUtil.classNoticeSend(item.getOpenid(), item.getSendee(), 
								record.getSchoolName(), record.getSender(), content, 
								record.getTemplateCode(), currReqUrl);
					} else if(record.getNoticeType() == NoticeType.NOTICE_HOMEWORK.getCode()) {
						TemplateUtil.homeworkNoticeSend(item.getOpenid(), item.getSendee(), 
								record.getSender(), reqVO.getSubject(), content, record.getTemplateCode(), currReqUrl);
					} else {
						String sendeeStr = item.getSendee() + SendeeType.getValue(item.getSendeeType());
						if(record.getNoticeType() == NoticeType.NOTICE_FILEAROUND.getCode()){
							if(GuideStatus.SENDED.getCode().equals(record.getGuideStatus())) {
								sendeeStr += "，您收到了一条校长批示的文件传阅通知，请查阅";
							}else {
								sendeeStr += "，您收到了一条文件传阅通知，请查阅";
							}
						}
						TemplateUtil.schoolNoticeSend(item.getOpenid(), sendeeStr, 
								record.getSchoolName(), record.getSender(), content, 
								record.getTemplateCode(), currReqUrl);
					}
				}
	        } catch (Exception e) { 
	            e.printStackTrace(); 
	        }
		}
	}

	@Override
	public List<NoticeRecordView> selectListByParam(NoticeQueryVO vo) {
		return noticeRecordMapper.selectListByParam(vo);
	}

	@Override
	public List<NoticeRecordView> selectViewListByPage(Page<NoticeRecordView> page) {
		return noticeRecordMapper.selectViewListByPage(page);
	}
	
	@Override
	public List<NoticeRecord> selectListByPage(Page<NoticeRecord> page) {
		return noticeRecordMapper.selectListByPage(page);
	}

	@Override
	public List<NoticeRecordView> selectCountForSendee(NoticeQueryVO vo) {
		return noticeRecordMapper.selectCountForSendee(vo);
	}

	@Override
	public NoticeRecordView selectViewByNoticeId(NoticeQueryVO vo) {
		return noticeRecordMapper.selectViewByNoticeId(vo);
	}

	@Override
	public NoticeRecordView selectByParam(NoticeQueryVO vo) {
		return noticeRecordMapper.selectByParam(vo);
	}

	@Override
	public List<NoticeRecord> selectListForFileAroundByPage(Page<NoticeRecord> page) {
		return noticeRecordMapper.selectListForFileAroundByPage(page);
	}

	@Override
	public List<NoticeRecord> selectListForFileAroundByPage1(Page<NoticeRecord> page) {
		return noticeRecordMapper.selectListForFileAroundByPage1(page);
	}

}
